﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace ClientAPI
{
    class Chat
    {
        /// <summary>
        /// there is a major flaw all chat is held in memory currently will overload the memory
        /// </summary>

        private Dictionary<string, string[]> chatDictionary = new Dictionary<string, string[]>();

        public string getLog(string userName)
        {
            string chatlog = "";
            string[] tempArray;
            if(!chatDictionary.TryGetValue(userName, out tempArray))
            {
                System.Diagnostics.Debug.WriteLine("ChatArray import error!!!");
            }
            else
            {
                for (int i = 0; i < tempArray.Length; i++)
                {
                    chatlog += tempArray[i] + Environment.NewLine;
                }
            }
            return chatlog;
        }

        public void ChatFunction(string user, string message)
        {
            if (chatDictionary.ContainsKey(user))
                AddMessage(user, message);
            else
                NewChat(user, message);
        }

        private void NewChat(string user, string message)
        {
            string[] tempArray = new string[1];
            tempArray[0] = user + ": " + message;
            chatDictionary.Add(user, tempArray);
        }

        private void AddMessage(string user, string message)
        {
            string[] importArray = new string[0];
            string[] tempArray;

            if (chatDictionary.TryGetValue(user, out importArray))
            {
                chatDictionary.Remove(user);
                tempArray = new string[importArray.Length+1];
                for (int i = 0; i <= importArray.Length-1; i++)
                {
                    tempArray[i] = importArray[i];
                }

                tempArray[importArray.Length] = user + ": " + message;
                chatDictionary.Add(user, tempArray);
            }
        }
    }
}
